/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller;

import com.thienloc.omap.entity.ServiceSuggestion;
import com.thienloc.omap.session.ServiceSuggestionFacade;
import com.thienloc.omap.util.JsfUtil;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class ServiceSuggestAjaxBean extends BaseBean implements Serializable {

    @EJB
    private ServiceSuggestionFacade serviceSuggestionFacade;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public void processXhr() {
        String origin = JsfUtil.getRequestParameter("origin");
        if (origin.equals("fillHelpContentMenu")) {
            fillHelpContentMenu();
        } else if (origin.equals("autoCompleteFullComand")) {
            autoCompleteFullComand();
        }
    }

    private void returnResponse(String responseText) {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(responseText);
        } catch (Exception ex) {
            String error = "Lỗi! ";
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage(error, ex.getMessage());
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    private void autoCompleteFullComand() {
        try {
            String term = JsfUtil.getRequestParameter("term").toUpperCase();
            List<String> suggests = serviceSuggestionFacade.findAllAlikeFullCommand(term);

            StringBuilder sb = new StringBuilder("[ \"");
            if (suggests != null && !suggests.isEmpty()) {
                for (String suggest : suggests) {
                    sb.append(suggest);
                    sb.append("\", \"");
                }
                sb.delete(sb.lastIndexOf("\", \""), sb.length());
            }
            sb.append("\" ]");

            returnResponse(sb.toString());
        } catch (Exception ex) {
            String error = "Lỗi! ";
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage(error, ex.getMessage());
        }
    }

    private void fillHelpContentMenu() {
        try {
            String fullCommand = JsfUtil.getRequestParameter("fullCommand");

            List<ServiceSuggestion> serviceSuggestions = serviceSuggestionFacade.findByFullCommand(fullCommand);
            StringBuilder sb = new StringBuilder();
            for (ServiceSuggestion serviceSuggestion : serviceSuggestions) {
                sb.append("<option value='")
                        .append(serviceSuggestion.getId())
                        .append("'>")
                        .append(serviceSuggestion.getShortHelpContent())
                        .append("</option>");
            }
            returnResponse(sb.toString());
        } catch (Exception ex) {
            String error = "Lỗi! ";
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage(error, ex.getMessage());
        }
    }
}
